package core.cwm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import core.obj.Object;
import core.sub.Company;

public class CompanyRecord {
	private List<Company> companies;
	private Map<String, CompanyDataSet> companyData;
	
	static private CompanyRecord companyRecords = null;
	
	private CompanyRecord() {
		companyData = new HashMap<String, CompanyDataSet>();
		companies = new ArrayList<Company>();
	}
	
	public static CompanyRecord getInstance() {
		if(companyRecords == null)
			companyRecords = new CompanyRecord();
		return companyRecords;
	}
	
	public CompanyDataSet getCompanyDataSet(Company company) {
		if(companyData.containsKey(company.getID()))
			return companyData.get(company.getID());
		
		return null;
	}
	
	public void addCompanyDataSet(Company company, CompanyDataSet data) {
		if(!companies.contains(company)) {
			companies.add(company);
		}
		companyData.put(company.getID(), data);
	}
	
	/**
	 * Return the company which obj belongs to
	 * @param obj
	 * @return
	 */
	public Company lookup(Object obj) {
		Iterator<String> CIDs = companyData.keySet().iterator();
		CompanyDataSet CData = null;
		String C;
		while(CIDs.hasNext()) {
			C=CIDs.next();
			CData = companyData.get(C);
			if(CData.contains(obj)) {
				for(int i=0;i<companies.size();i++) {
					if(companies.get(i).getID().equals(C))
						return companies.get(i);
				}
			}
		}		
		return null;
	}
	
	public Company lookup(String companyID) {
		for(Company comp: companies) {
			if(comp.getID().equals(companyID))
				return comp;
		}		
		return null;
	}
	
	public Object findObject(String objID) {
		Object obj = null;
		Iterator<CompanyDataSet> datas = companyData.values().iterator();
		CompanyDataSet data=null;
		while(datas.hasNext()) {
			data=datas.next();
			obj = data.findObject(objID);
			if(obj != null)
				break;
		}
		
		return obj;
	}
}
